<template>
  <div
    style="
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      padding: 20px;
      display: flex;
      flex-direction: column;
    "
  >
    <div>
      <el-form>
        <el-form-item label="日期">
          <el-date-picker
            v-model="datetime"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd 00:00:00"
            :clearable="false"
            @change="getPatrolByFormData(true, true)"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="班次">
          <el-radio-group
            v-model="upDown.value"
            @input="getPatrolByFormData(true, true)"
          >
            <el-radio
              v-for="radio of upDown.radioList"
              :key="radio.label"
              :label="radio.value"
              >{{ radio.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="员工">
          <div style="width: 100%">
            <el-checkbox-group
              v-model="user.value"
              @change="getPatrolByFormData(false, true)"
            >
              <div style="display: flex; align-items: center; column-gap: 20px">
                <div
                  v-for="marker of user.markers"
                  :key="marker.value"
                  style="display: flex; align-items: center; column-gap: 10px"
                >
                  <el-image
                    :src="marker.iconPath"
                    style="width: 30px; height: 30px"
                    :preview-src-list="[marker.iconPath]"
                  ></el-image>
                  <div
                    style="width: 20px; height: 20px; border-radius: 10px"
                    :style="{ backgroundColor: marker.color }"
                  ></div>
                  <el-checkbox :label="marker.userUuid">{{
                    marker.name
                  }}</el-checkbox>
                </div>
              </div>
            </el-checkbox-group>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div style="flex: 1; min-height: 0">
      <tlbs-map
        ref="myMap"
        style="width: 100%; height: 100%"
        api-key="OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"
        :minZoom="4"
      >
        <tlbs-multi-marker
          :geometries="computedMarkers.geometries"
          :styles="computedMarkers.styles"
        />
        <tlbs-multi-polyline
          :geometries="computedPolylines.geometries"
          :styles="computedPolylines.styles"
        />
      </tlbs-map>
    </div>
  </div>
</template>

<script>
import dayjs from "dayjs";
import isSameOrAfter from "dayjs/plugin/isSameOrAfter";
import isSameOrBefore from "dayjs/plugin/isSameOrBefore";
dayjs.extend(isSameOrAfter);
dayjs.extend(isSameOrBefore);
import { getPatrolByFormData } from "@/api/patrol";
import _ from "lodash";
import { showDataNg, showDataOk } from "@/utils/message";
import { time } from "mockjs/src/mock/random/date";
export default {
  mounted() {
    this.datetime = this.getCurrentDatetime();
    this.timeout = setTimeout(() => {
      clearTimeout(this.timeout);
      this.timeout = null;
      this.getPatrolByFormData(true, true);
    }, 2000);
  },
  computed: {
    polylines() {
      let otherPolyline = this.markerAndPolyline.map((item) => {
        return item.polylines;
      });
      otherPolyline = _.flattenDeep(otherPolyline);
      return otherPolyline;
    },
    computedPolylines() {
      let geometries = this.polylines.map((polyline) => {
        return {
          styleId: polyline.userUuid,
          paths: polyline.points.map((point) => {
            return new window.TMap.LatLng(point.latitude, point.longitude);
          }),
        };
      });
      let styles = {};
      for (let i = 0; i < this.polylines.length; i++) {
        let polyline = this.polylines[i];
        styles[polyline.userUuid] = new window.TMap.PolylineStyle({
          color: polyline.color,
          showArrow: true,
          width: 5,
        });
      }
      return {
        geometries,
        styles,
      };
    },
    computedMarkers() {
      let geometries = this.markers.map((marker) => {
        return {
          styleId: marker.userUuid,
          position: new window.TMap.LatLng(marker.latitude, marker.longitude),
        };
      });
      let styles = {};
      for (let i = 0; i < this.markers.length; i++) {
        let marker = this.markers[i];
        styles[marker.userUuid] = new window.TMap.MarkerStyle({
          width: 30,
          height: 30,
          anchor: "center",
          src: marker.iconPath,
        });
      }
      return {
        geometries,
        styles,
      };
    },
  },

  methods: {
    setScale() {
      let points = this.polylines.map((polyline) => {
        return polyline.points;
      });
      points = _.flattenDeep(points);
      let top = Number.MIN_SAFE_INTEGER;
      let bottom = Number.MAX_SAFE_INTEGER;
      let left = Number.MAX_SAFE_INTEGER;
      let right = Number.MIN_SAFE_INTEGER;
      for (let i = 0; i < points.length; i++) {
        let point = points[i];
        let lng = point.longitude;
        let lat = point.latitude;
        if (lng < left) {
          left = lng;
        }
        if (lng > right) {
          right = lng;
        }
        if (lat < bottom) {
          bottom = lat;
        }
        if (lat > top) {
          top = lat;
        }
      }
      let bounds = {
        sw: new window.TMap.LatLng(bottom, left),
        ne: new window.TMap.LatLng(top, right),
      };
      let bound = new window.TMap.LatLngBounds(bounds.sw, bounds.ne);
      function fit(map) {
        if (map) {
          map.fitBounds(bound);
          return;
        } else {
          map = this.$refs.myMap.map;
          fit(map);
        }
      }
      fit(this.$refs.myMap.map);
    },
    setMarkers() {
      this.user.markers = this.markerAndPolyline.map((item) => {
        return item.marker;
      });
    },
    setRealMarkers() {
      this.markers = this.markerAndPolyline.map((item) => {
        return item.marker;
      });
    },
    async getPatrolByFormData(isUpdateMarker, showMessage) {
      function getRandomColor() {
        function getRandomHex() {
          return parseInt((Math.random() * 200 + 50).toFixed(0)).toString(16);
        }
        let result = "#";
        for (let i = 1; i <= 3; i++) {
          result = result + getRandomHex();
        }
        return result;
      }
      try {
        let datetime = "";
        if (this.upDown.value === "1") {
          datetime = dayjs(this.datetime).format("YYYY-MM-DD 12:00:00");
        } else if (this.upDown.value === "2") {
          datetime = dayjs(this.datetime).format("YYYY-MM-DD 24:00:00");
        }
        let start = "";
        let end = "";
        if (datetime) {
          let currentDayjs = dayjs(datetime);
          let baseDayjsStart = dayjs(
            currentDayjs.format("YYYY-MM-DD 07:30:00")
          );
          let baseDayjsEnd = dayjs(currentDayjs.format("YYYY-MM-DD 19:30:00"));
          let upEnd = dayjs(currentDayjs.format("YYYY-MM-DD 24:00:00"));
          let downStart = dayjs(currentDayjs.format("YYYY-MM-DD 00:00:00"));

          let isMorning =
            currentDayjs.isSameOrAfter(baseDayjsStart) &&
            currentDayjs.isBefore(baseDayjsEnd);
          if (isMorning) {
            start = currentDayjs.format("YYYY-MM-DD 07:30:00");
            end = currentDayjs.format("YYYY-MM-DD 19:29:59");
          } else {
            let isUp =
              currentDayjs.isSameOrAfter(baseDayjsEnd) &&
              currentDayjs.isSameOrBefore(upEnd);
            let isDown =
              currentDayjs.isSameOrAfter(downStart) &&
              currentDayjs.isBefore(baseDayjsStart);

            if (isUp) {
              start = currentDayjs.format("YYYY-MM-DD 19:30:30");
              end = currentDayjs.add(1, "day").format("YYYY-MM-DD 07:29:59");
            } else if (isDown) {
              start = currentDayjs
                .subtract(1, "day")
                .format("YYYY-MM-DD 19:30:30");
              end = currentDayjs.format("YYYY-MM-DD 07:29:59");
            }
          }
        } else {
          let currentDayjs = dayjs(this.datetime);
          start = currentDayjs.format("YYYY-MM-DD 07:30:00");
          end = currentDayjs.add(1, "day").format("YYYY-MM-DD 07:29:59");
        }
        if (isUpdateMarker) {
          this.user.value = [];
          this.user.markers = [];
        }
        let result = await getPatrolByFormData({
          datetimeRange: [start, end],
          userUuidList: this.user.value,
        });
        let patrolGroup = _.groupBy(result.data.list, "userUuid");
        let markerAndPolyline = [];
        let id = 0;
        for (let [userUuid, allList] of Object.entries(patrolGroup)) {
          let tempAllList = allList.map((item) => {
            return {
              ...item,
              polyline: JSON.parse(item.polyline),
            };
          });
          let color = this.user.markers.find(
            (marker) => marker.userUuid === userUuid
          )
            ? this.user.markers.find((marker) => marker.userUuid === userUuid)
                .color
            : getRandomColor();
          let allPolyline = [];
          for (let i = 0; i < tempAllList.length; i++) {
            let item = tempAllList[i];
            let polyline = item.polyline;
            let tempPolyline = {
              id: ++id,
              points: polyline,
              color,
              width: 5,
              arrowLine: false,
              userUuid,
            };
            if (userUuid === this.userUuid) {
              if (i < tempAllList.length - 1) {
                allPolyline.push(tempPolyline);
              }
            } else {
              allPolyline.push(tempPolyline);
            }
          }
          if (allPolyline.length === 0) {
            continue;
          }
          let points = allPolyline[allPolyline.length - 1].points;
          let longitude = points[points.length - 1].longitude;
          let latitude = points[points.length - 1].latitude;
          markerAndPolyline.push({
            polylines: allPolyline,
            marker: {
              id: ++id,
              longitude,
              latitude,
              iconPath: tempAllList[tempAllList.length - 1].avatar,
              rotate: 0,
              anchor: { x: 0.5, y: 0.5 },
              width: "40rpx",
              height: "40rpx",
              color,
              userUuid,
              name: tempAllList[tempAllList.length - 1].name,
            },
          });
        }
        let selfIndex = markerAndPolyline.findIndex((item) => {
          return item.marker.userUuid === this.userUuid;
        });
        if (selfIndex !== -1) {
          let self = markerAndPolyline.splice(selfIndex, 1);
          markerAndPolyline = [...markerAndPolyline, ...self];
        }
        this.markerAndPolyline = markerAndPolyline;
        if (isUpdateMarker) {
          this.setMarkers();
        }
        this.setRealMarkers();
        this.setScale();
        if (showMessage) {
          showDataOk();
        }
      } catch (error) {
        if (showMessage) {
          showDataNg(error);
        }
      }
    },
    getCurrentDatetime() {
      return dayjs().format("YYYY-MM-DD 00:00:00");
    },
  },
  data() {
    return {
      timeout: null,
      markerAndPolyline: [],
      markers: [],
      datetime: "",
      upDown: {
        value: "",
        radioList: [
          {
            label: "忽略",
            value: "",
          },
          {
            label: "白班",
            value: "1",
          },
          {
            label: "夜班",
            value: "2",
          },
        ],
      },
      user: {
        value: [],
        markers: [],
      },
    };
  },
};
</script>
